package ai.people.platform.graph.service;

import ai.people.core.nebula.properties.ConnectProperties;
import ai.people.netmon.framework.domain.graph.GraphStatistics;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.Collection;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * @author zhenglin
 * @date 2022/6/30
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class StatisticsService {

    private final ConnectProperties connectProperties;

    private final GraphStatisticsService graphStatisticsService;

    private final ExecutorService service;

    public final ArrayBlockingQueue<String> queue = new ArrayBlockingQueue<>(2048);


    public void put(String vid){
        service.execute(()-> {
            try {
                queue.put(vid);
            } catch (InterruptedException e) {
                log.error(e.getMessage(), e);
            }
        });
    }

    public void put(Collection<String> vids){
        service.execute(()-> {
            try {
                for (String vid : vids) {
                    queue.put(vid);
                }
            } catch (InterruptedException e) {
                log.error(e.getMessage(), e);
            }
        });
    }


    @PostConstruct
    public void log() {
        service.execute(()->{
            while(true){
                while (!queue.isEmpty()){
                    try {
                        String vid = queue.take();
                        if (StringUtils.isBlank(vid)){
                            continue;
                        }
                        GraphStatistics statistics = new GraphStatistics();
                        statistics.setVid(vid);
                        statistics.setSpace(connectProperties.getSpaceName());
                        graphStatisticsService.save(statistics);
                    } catch (InterruptedException e) {
                        log.error(e.getMessage(), e);
                    }
                }
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    log.error(e.getMessage(), e);
                }
            }

        });
    }

}
